package com.um.jdy.common.charge.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.*;
import cn.hutool.core.util.NumberUtil;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.charge.entity.dto.PlaceRange;
import com.um.jdy.common.charge.entity.po.OrderPlace;
import com.um.jdy.common.charge.entity.po.OrderPlaceFee;
import com.um.jdy.common.charge.entity.po.OrderPlaceTime;
import com.um.jdy.common.charge.service.OrderPlaceFeeService;
import com.um.jdy.common.charge.service.OrderPlaceTimeService;
import com.um.springboot.starter.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import com.um.springboot.starter.orm.service.BaseEntityServiceImpl;
import com.um.jdy.common.charge.service.EvOrderService;
import com.um.jdy.common.charge.dao.EvOrderDao;
import com.um.jdy.common.charge.entity.po.EvOrder;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务实现类：汽车订单扩展表
 */
@Service
@Slf4j
public class EvOrderServiceImpl extends BaseEntityServiceImpl<EvOrderDao,EvOrder>  implements EvOrderService{

    @Autowired
    OrderPlaceFeeService orderPlaceFeeService;

    @Autowired
    OrderPlaceTimeService orderPlaceTimeService;

    /**
     * 保存订单占位费
     * @param orderPlace
     * @param evOrder
     * @return
     */
    public Integer savePlaceFee(OrderPlace orderPlace, EvOrder evOrder, boolean saveRow){
        if (!orderPlace.getStatus().equals(YesOrNo.Yes.name())) {//不收占位费
            return 0;
        }

        if(evOrder.getPlaceBeginTime().after(evOrder.getPlaceEndTime())){
            return 0;
        }

        // 跨天处理，每天的开始、结束时间组成集合
        List<PlaceRange> placeRangeList = new ArrayList<>();
        PlaceRange placeRange = null;
        List<DateTime> days = DateUtil.rangeToList(DateUtil.beginOfDay(evOrder.getPlaceBeginTime()),
                DateUtil.beginOfDay(evOrder.getPlaceEndTime()), DateField.DAY_OF_YEAR);

        for (int index = 0; index < days.size(); index++) {
            placeRange = new PlaceRange();
            if(index == 0){
                placeRange.setStartTime(evOrder.getPlaceBeginTime());
                placeRange.setFreeDuration(orderPlace.getFreeDuration());
            }else{
                placeRange.setStartTime(DateUtil.beginOfDay(days.get(index)));
            }
            if(index + 1 == days.size()){
                placeRange.setEndTime(evOrder.getPlaceEndTime());
            }else {
                placeRange.setEndTime(DateUtil.endOfDay(days.get(index)));
            }
            placeRangeList.add(placeRange);
        }

        LocalTime startTime = DateUtil.toLocalDateTime(DateUtil.offsetMinute(evOrder.getPlaceBeginTime(),
                orderPlace.getFreeDuration())).toLocalTime();
        LocalTime endTime = DateUtil.toLocalDateTime(evOrder.getPlaceEndTime()).toLocalTime();

        List<OrderPlaceTime> timeList = orderPlaceTimeService.getListBySqlName("get_order_place_time_list",
                new Object[]{startTime.toString(), endTime.toString(), evOrder.getChargeOrderId()});

        int placeFee = placeRangeList.stream().mapToInt(range -> savePlaceFeeByRange(timeList, range, saveRow)).sum();
        return placeFee;
    }

    /**
     * 保存订单占位费
     * @param timeList
     * @param placeRange
     * @return
     */
    public Integer savePlaceFeeByRange(List<OrderPlaceTime> timeList, PlaceRange placeRange, boolean saveRow){
        LocalTime startTime = DateUtil.toLocalDateTime(placeRange.getStartTime()).toLocalTime();
        LocalTime endTime = DateUtil.toLocalDateTime(placeRange.getEndTime()).toLocalTime();
        int placeFee = 0;
        OrderPlaceFee orderPlaceFee = null;
        String dateStr = DateUtil.format(placeRange.getStartTime(), DatePattern.NORM_DATE_PATTERN) + " ";

        for (int index = 0; index < timeList.size(); index++) {
            orderPlaceFee = BeanUtil.toBean(timeList.get(index), OrderPlaceFee.class);
            orderPlaceFee.setCreateTime(DateUtil.date());
            if(index == 0){
                orderPlaceFee.setPlaceStartTime(DateUtil.parse(dateStr + startTime.toString()));
            }else{
                orderPlaceFee.setPlaceStartTime(DateUtil.parse(dateStr + orderPlaceFee.getStartTime().toString() + ":00"));
            }
            if(index + 1 == timeList.size()){
                orderPlaceFee.setPlaceEndTime(DateUtil.parse(dateStr + endTime.toString()));
            }else {
                orderPlaceFee.setPlaceEndTime(DateUtil.parse(dateStr + orderPlaceFee.getEndTime().toString() + ":00"));
            }
            long between = DateUtil.between(orderPlaceFee.getPlaceStartTime(),
                    orderPlaceFee.getPlaceEndTime(), DateUnit.MINUTE);
            orderPlaceFee.setPlaceMinutes((int) between);

            int amount = 0;
            if(index == 0){
                amount = (int) NumberUtil.mul(Math.max(0,between - StringUtil.toInt(placeRange.getFreeDuration())),
                        orderPlaceFee.getPrice().intValue());
            }else{
                amount = (int) NumberUtil.mul(between, orderPlaceFee.getPrice().intValue());
            }

            orderPlaceFee.setAmount(amount);
            if(saveRow){
                orderPlaceFeeService.saveRow(orderPlaceFee);
            }

            placeFee += amount;
        }

        return placeFee;
    }

}
